<template>
  <div class="components-container fns-user">

  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-row>
      <el-col :span="20">
      <el-form-item label="分配岗位">
      <el-select v-model="formInline.roleId" placeholder="请选择岗位" clearable>
        <el-option
          v-for="(item, index) in rolesOptions"
          :key="index"
          :label="item.keyName"
          :value="item.valueName">
        </el-option>
      </el-select>
      </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="formInline.username" :clearable="true" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <template>
            <el-select v-model="formInline.status" clearable placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryList" size="medium" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="4" style="text-align:right;">
        <el-button type="primary" size="medium" icon="el-icon-plus" @click="added" v-show="showAdd">新增</el-button>
      </el-col>
    </el-row>
  </el-form>

      <template>
        <el-table v-loading="loading" :data="tableData" border style="width: 100%">
          <el-table-column prop="account" align="center" label="账号"></el-table-column>
          <el-table-column prop="username"align="center" label="用户名称"></el-table-column>
          <el-table-column prop="phone" align="center" label="手机号码"></el-table-column>
          <el-table-column prop="displayName" align="center" label="分配岗位"></el-table-column>
          <el-table-column align="center" label="状态" min-width="80">
            <template slot-scope="scope">
              <span>{{scope.row.status?'启用':'停用'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updatedOn" align="center" label="修改时间"></el-table-column>
          <el-table-column align="center" width="100" label="操作">
            <template slot-scope="scope">
              <el-tooltip content="修改" placement="top" v-show="showUpdate">
                <a @click="edit(scope.$index, scope.row)">
                  <i class="el-icon-edit-outline"></i>
                </a>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- ========分页======-->
    <pages v-on:_pageChange="_pageChange" :total="total"></pages>

      <el-dialog
        title="新增用户"
        :visible.sync="dialogVisible"
        width="780px"
        :before-close="handleClose"
        :close-on-click-modal="false">
        <el-form label-width="100px" :model="formAdd" ref="formAdd" :rules="rules">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账号：" prop="account">
                <el-input v-model="formAdd.account" placeholder="请输入账号" :minlength="4" :maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名称：" prop="username">
                <el-input v-model="formAdd.username" placeholder="请输入用户名称" :maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="密码：" prop="psd">
                <el-input type="password" v-model="formAdd.psd" auto-complete="off" placeholder="请输入密码" :minlength="6" :maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="确认密码：" prop="confirmPsd">
                <el-input type="password" v-model="formAdd.confirmPsd" auto-complete="off" placeholder="请再次输入密码" :minlength="6" :maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号码：" prop="phone">
                <el-input v-model="formAdd.phone" placeholder="请输入手机号码" :minlength="11" :maxlength="11" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分配岗位：" prop="roleId">
                <el-select v-model="formAdd.roleId" placeholder="可搜索选择" filterable clearable style="width:100%;">
                  <el-option
                    v-for="(item, index) in rolesOptions"
                    :key="index"
                    :label="item.keyName"
                    :value="item.valueName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="状态：">
            <el-radio-group v-model="formAdd.status">
              <el-radio :label="1">启 用</el-radio>
              <el-radio :label="0">停 用</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="状态：">
            <el-switch
              v-model="formAdd.status"
              active-value="1"
              active-text="启用"
              inactive-value="0"
              inactive-text="停用"
              active-color="##13ce66">
            </el-switch>
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAdd()">提 交</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="修改用户"
        :visible.sync="editVisible"
        width="780px"
        :before-close="handleClose"
        :close-on-click-modal="false">
        <el-form label-width="100px" :model="formEdit" ref="formEdit" :rules="rulesEdit">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账号：" prop="account">
                <el-input v-model="formEdit.account" placeholder="请输入账号" :minlength="4" :maxlength="20" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名称：" prop="username">
                <el-input v-model="formEdit.username" placeholder="请输入用户名称" :maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="密码：">
                <el-input type="password" v-model="formEdit.psd" auto-complete="off" placeholder="请输入密码" :minlength="6" :maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="确认密码：">
                <el-input type="password" v-model="formEdit.confirmPsd" auto-complete="off" placeholder="请再次输入密码" :minlength="6" :maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24" class="redco">注：如果不需要修改密码请不要输入，一旦输入默认为修改密码</el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号码：" prop="phone">
                <el-input v-model="formEdit.phone" placeholder="请输入手机号码" :minlength="11" :maxlength="11" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分配岗位：" prop="roleId">
                <el-select v-model="formEdit.roleId" placeholder="可搜索选择" filterable clearable style="width:100%;">
                  <el-option
                    v-for="(item, index) in rolesOptions"
                    :key="index"
                    :label="item.keyName"
                    :value="item.valueName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="状态：">
            <el-radio-group v-model="formEdit.status">
              <el-radio :label="1">启 用</el-radio>
              <el-radio :label="0">停 用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEdit()">提 交</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import * as api from '@/api/system'
import { findMenu, findSubMenu, findBtn } from '@/utils/btn'
import pages from '../../components/page/page'
// import { mapState } from 'vuex'
export default {
  data() {
    return {
      loading: false,
      total: 0,
      dialogVisible: false,
      editVisible: false,
      page: {
        index: 1,
        size: 10
      },
      formInline: {
        roleId: '',
        username: '',
        status: ''
      },
      options: [{
        value: '1',
        label: '启用'
      }, {
        value: '0',
        label: '停用'
      }],
      tableData: [],
      formAdd: {
        account: '',
        roleId: '',
        username: '',
        psd: '',
        confirmPsd: '',
        phone: '',
        status: 1
      },
      formEdit: {
        account: '',
        roleId: '',
        username: '',
        psd: '',
        confirmPsd: '',
        phone: '',
        status: ''
      },
      rolesOptions: [],
      editRolesOptions: [],
      rules: {
        account: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { pattern: /^[0-9a-zA-Z_]{1,}$/, message: '请勿输入特殊字符', trigger: 'blur' },
          { min: 4, max: 20, message: '长度为 4 到 20 个', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          { max: 20, message: '长度最多不能超过20 个字符', trigger: 'blur' }
        ],
        psd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度为 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPsd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度为 6 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入11位手机号码', trigger: 'blur' },
          { pattern: /^1[34578]\d{9}$/, message: '请输入正确的11位手机号码' }
        ],
        roleId: [
          { required: true, message: '请选择岗位', trigger: 'change' }
        ]
      },
      rulesEdit: {
        account: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { min: 4, max: 20, message: '长度为 4 到 20 个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          { max: 20, message: '长度最多不能超过20 个字符', trigger: 'blur' }
        ],
        psd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度为 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPsd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度为 6 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入11位手机号码', trigger: 'blur' },
          { pattern: /^1[34578]\d{9}$/, message: '请输入正确的11位手机号码' }
        ],
        roleId: [
          { required: true, message: '请选择岗位', trigger: 'change' }
        ]
      }
    }
  },
  components: {
    pages
  },
  created() {
    this.queryList()
    // 初始化所有岗位
    api.listRole().then((res) => {
      this.rolesOptions = res.data
      console.log(this.rolesOptions)
    })
  },
  computed: {
    showAdd() {
      let menu = findMenu('系统管理')
      let subMenu = findSubMenu(menu.children, '公司用户管理')
      if (findBtn(subMenu.children, '新增')) {
        return true
      } else {
        return false
      }
    },
    showUpdate() {
      let menu = findMenu('系统管理')
      let subMenu = findSubMenu(menu.children, '公司用户管理')
      if (findBtn(subMenu.children, '修改')) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    // 分页和列表
    _pageChange(val, flag) {
      var arr = []
      if (flag === 'size') {
        this.page.index = val
        this.queryList()
      } else {
        arr.push(val)
        this.page.index = 1
        this.page.size = arr[0]
        this.queryList()
      }
    },
    // 获取列表数据
    queryList(val) {
      this.loading = true
      var pages = {
        index: this.page.index,
        size: this.page.size || val
      }
      var data = Object.assign({}, this.formInline, pages)
      api.userList(data).then((res) => {
        if (+res.code === 0) {
          this.tableData = res.data.rows
          this.total = +res.data.total
        }
        this.loading = false
      }).catch(err => {
        console.log(err)
        this.loading = false
      })
    },
    // 点击弹出新增窗口
    added() {
      this.modalTitle = '新增'
      this.dialogVisible = true
      this.formAdd.status = 1
      this.formAdd.account = ''
      this.formAdd.roleId = ''
      this.formAdd.phone = ''
      this.formAdd.username = ''
      this.formAdd.psd = ''
      this.formAdd.confirmPsd = ''
    },
    // 新增
    handleAdd() {
      this.$refs['formAdd'].validate((valid) => {
        if (this.formAdd.confirmPsd !== this.formAdd.psd) {
          Message({
            message: '两次输入的密码不一致',
            type: 'error',
            duration: 5 * 1000
          })
          return
        }
        if (valid) {
          delete this.formAdd.confirmPsd
          api.userAdd(this.formAdd).then(res => {
            this.formAdd.confirmPsd = this.formAdd.psd
            if (+res.code === 0) {
              this.formAdd = {}
              this.queryList()
              this.dialogVisible = false
            }
          })
          // .catch(err => {
          //   console.log(err)
          //   this.formAdd.confirmPsd = this.formAdd.psd
          //   this.queryList()
          // })
        } else {
          return
        }
      })
    },
    // 根据ID获取用户信息
    edit(index, row) {
      this.formEdit.status = ''
      this.modalTitle = '修改'
      this.editVisible = true
      const id = { id: row.id }
      api.userUpdate(id).then((res) => {
        if (+res.code === 0) {
          var rowData = res.data
          this.formEdit.id = rowData.id || ''
          this.formEdit.account = rowData.account || ''
          this.formEdit.username = rowData.username || ''
          this.formEdit.confirmPsd = this.formEdit.psd = rowData.psd || ''
          this.formEdit.phone = rowData.phone || ''
          this.formEdit.roleId = rowData.roleId || ''
          this.formEdit.status = Number(rowData.status || '')
          this.isValue()
        }
      })
    },
    // 修改
    handleEdit() {
      this.$refs['formEdit'].validate((valid) => {
        if (this.formEdit.confirmPsd !== this.formEdit.psd) {
          Message({
            message: '两次输入的密码不一致',
            type: 'error',
            duration: 5 * 1000
          })
          return
        }
        if (valid) {
          delete this.formEdit.confirmPsd
          api.editUpdate(this.formEdit).then(res => {
            this.formEdit.confirmPsd = this.formEdit.psd
            if (+res.code === 0) {
              this.queryList()
              this.editVisible = false
            }
          }).catch(err => {
            console.log(err)
            this.formEdit.confirmPsd = this.formEdit.psd
            this.queryList()
          })
        } else {
          return
        }
      })
    },
    isValue() {
      var arr = this.rolesOptions.filter(item => {
        return item.valueName === this.formEdit.roleId
      })
      if (arr.length === 0) {
        this.formEdit.roleId = ''
      }
    },
    // 关闭弹窗
    handleClose(done) {
      this.dialogVisible = false
      this.editVisible = false
    }
  }
}
</script>
<style lang="scss">
.fns-user {
  .redco {
    font-size:14px;
    color:#f56c6c;
    padding-left:112px!important;
  }
  .el-form-item{margin-bottom:22px;}
}

</style>
